# -*- coding: utf-8 -*-
import copy
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from datetime import datetime
from zc_core.client.mongo_client import Mongo
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.batch_gen import time_to_batch_no, batch_to_year
from zc_core.util.http_util import retry_request
from plap_deli.rules import parse_order_detail
from plap_deli.utils.login import SeleniumLogin
from zc_core.spiders.base import BaseSpider


class OrderDetailSpider(BaseSpider):
    name = 'order_detail'
    custom_settings = {
        'CONCURRENT_REQUESTS': 8,
        'DOWNLOAD_DELAY': 0.1,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 8,
        'CONCURRENT_REQUESTS_PER_IP': 8,
    }
    # 常用链接
    item_url = 'http://mall.plap.cn/npc/orders/{}'

    def __init__(self, batchNo=None, delta_hour=-12, *args, **kwargs):
        super(OrderDetailSpider, self).__init__(batchNo=batchNo, hourOffset=delta_hour, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)

    def start_requests(self):
        cookies = SeleniumLogin().get_cookies('order')
        # cookies = {'_session_id': '71a48017949eecccf82ee53342cbe376'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        pool_list = Mongo().list('order_{}'.format(batch_to_year(self.batch_no)),
                                 query={'itemList': {'$exists': False}}, fields={'_id': 1, 'orderTime': 1})
        # pool_list = Mongo().list('order_{}'.format(batch_to_year(self.batch_no)), fields={'_id': 1, 'orderTime': 1})
        self.logger.info('目标：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            order_id = sku.get('_id')
            order_time = sku.get('orderTime')
            # 采集商品价格及状态
            yield Request(
                url=self.item_url.format(order_id),
                meta={
                    'reqType': 'order_item',
                    'batchNo': self.batch_no,
                    'orderId': order_id,
                    'orderTime': order_time,
                },
                cookies=cookies,
                callback=self.parse_order_detail,
                errback=self.error_back,
                priority=25,
            )

    # 处理ItemData
    def parse_order_detail(self, response):
        meta = response.meta
        order_id = meta.get('orderId')

        data = parse_order_detail(response)
        if data:
            self.logger.info('订单: order=%s, items=%s' % (order_id, len(data.get('itemList'))))
            yield data
        else:
            self.logger.error('空单: [%s]' % order_id)
